/**
 * 
 */
package xiaojian.toolkit.ebus.unit.fs;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import xiaojian.toolkit.ebus.unit.UnitSource;

/**
 * @author hp
 * 
 */
public class FilesystemUnitSource implements UnitSource {

	private static final Logger logger = LoggerFactory
			.getLogger(FilesystemUnitSource.class);
	private File file;
	private String template;
	private String type;

	public FilesystemUnitSource(File file) {
		this.file = file;
		try {
			template = file.getCanonicalPath();
		} catch (IOException e) {
			logger.error("FilesystemUnitSource.init file.getCanonicalPath", e);
		}
		if (null != template) {
			type = FilenameUtils.getExtension(template);
		}
	}

	@Override
	public String getName() {
		return file != null && file.exists() ? file.getName() : null;
	}

	/**
	 * @see com.skymobi.ebus.unit.UnitSource#getTemplate()
	 */
	public String getTemplate() {
		return template;
	}

	public InputStream getInputStream() {
		try {
			return new FileInputStream(file);
		} catch (FileNotFoundException e) {
			logger.error("getInputStream", e);
		}
		return null;
	}

	/**
	 * @see com.skymobi.ebus.unit.UnitSource#lastModified()
	 */
	public long lastModified() {
		return file.lastModified();
	}

	@Override
	public String toString() {
		return ToStringBuilder.reflectionToString(this,
				ToStringStyle.MULTI_LINE_STYLE);
	}

	public String getType() {
		return type;
	}

	/**
	 * @param type
	 *            the type to set
	 */
	public void setType(String type) {
		this.type = type;
	}

	/**
	 * @param name
	 *            the name to set
	 */
	public void setTemplate(String name) {
		this.template = name;
	}

	/**
	 * @see xiaojian.toolkit.ebus.unit.UnitSource#getExtendsProperties()
	 */
	@Override
	public Properties getExtendsProperties() {
		InputStream in;
		try {
			in = new FileInputStream(file);
		} catch (FileNotFoundException e) {
			logger.error("Cannot found file[" + file + "].", e);
			return new Properties();
		}
		Properties prop = new Properties();
		try {
			prop.load(in);
		} catch (IOException e) {
			logger.error("Load file[" + file + "] fail.", e);
			return new Properties();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
				}
			}
		}
		return prop;
	}

}
